<template>
  <swiper
    :vertical="!isFullScreen"
    :duration="swiperOptions.duration"
    :circular="swiperOptions.circular"
    :touchRatio="1"
    :current="swiperOptions.current"
    style="height: 100vh; z-index: 1999"
    :class="{ 'full-screen-swiper': isFullScreen }"
    @change="swiperChange"
  >
    <swiper-item v-for="item in curQueue" :key="item.episodes_id">
      <view
        class="main"
        style="height: 100%; z-index: 1"
        @click="onTapVideo"
      >
        <!-- 首尾，继续滑动，显示空屏 -->
        <block v-if="!item">
          <view
            style="
              width: 100vw;
              height: 100vh;
              z-index: 1;
              background-color: black;
            "
          />
        </block>
        <!-- 加载中 -->
        <block v-if="item.status === 'loading'">
          <view class="loading">
            <loading />
          </view>
        </block>
        <!-- 获取 video 失败 -->
        <block v-if="item.status === 'error'">
          <!-- <errPage
              needRetryBtn="false"
              errTitle="网络错误"
              errDesc="请检查网络连接后重试"
              errImage="../../static/network-err.png"
          /> -->
        </block>
        <!-- 渲染 video-player 组件 -->
        <block v-if="item.eid">
          <tt-video-player
            @timeupdate="timeUpdateHandler"
            @getsource="getsourceHandler"
            :enable-dark-water-mark="true"
            :cloud-type="1"
            version="1"
            :album-id="item.aid"
            :episode-id="item.eid"
            :id="item.id"
            :autoplay="true"
            style="width: 100vw; height: 100vh; z-index: 1"
            object-fit="contain"
            :show-fullscreen-btn="false"
            :show-play-btn="false"
            :vslide-gesture-in-fullscreen="false"
            :controls="false"
            @ended="nextVideo"
            @error="error"
            :poster="item.episodes_cover"
            :data-episode="item.episode"
          >
           <!-- 选集弹窗 -->
              <change-video-dialog
                ref="changeVideoDialogHandler"
                :currentVideo="item"
                :currentAblum="currentAblum"
                :needChangeVideo="showChangeVideoPopup"
                :total="allVideoData.length"
                @cancel="cancelChangeVideo"
                @episodesChangeHandler="onChangeEpisode"
            />
          </tt-video-player>

          <view class="info-con">
            <!-- 全屏按钮 -->
            <view
              v-if="item.horizontal_screen"
              :class="['full-screen-btn', { hidden: showChangeVideoPopup }]"
              @click="changeFullScreen"
              :data-fullscreeneid="item.eid"
              :data-fullscreencurrentvideo="item"
            >
              <image src="../../static/full-screen.png" />
              全屏观看
            </view>
            <!-- 底部剧名称 -->
            <view class="video-title">
              {{ currentAblum.ablum_name }}
            </view>
            <!-- 底部剧简介 -->
            <view class="video-text">
              <!-- <collapseText
                  :text="item.episodes_description"
                  :fontSize="30"
                  :fontColor="'rgba(255, 255, 255, 0.9)'"
              /> -->
            </view>
          </view>

          <!-- 操作区域 -->
          <view class="operate">
            <!-- 点赞 -->
            <view @likeHandler="likeHandler" :data-videoItem="item">
              <image
                :src="
                  item.likeActive
                    ? '../../static/Like_Shadow.png'
                    : '../../static/like.png'
                "
              ></image>
              <view class="oprarte-num"> {{ item.episodesLikes }}</view>
            </view>

            <!-- 收藏 -->
            <view @starHandler="starHandler" :data-videoItem="item">
              <image
                :src="
                  item.starActive
                    ? '../../static/Star_Shadow.png'
                    : '../../static/star.png'
                "
              ></image>
              <view class="oprarte-num"> {{ item.episodesChasing }}</view>
            </view>

            <!-- 分享 -->
            <view style="position: relative">
              <image src="../../static/share.png"> </image>
              <button
                style="
                  opacity: 0;
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 72rpx;
                  height: 72rpx;
                "
                @shareVideo="shareVideo"
                open-type="share"
                :data-videoItem="item"
              />
              <view class="oprarte-num"> {{ item.episodesShares }}</view>
            </view>
          </view>
          <!-- 选集区域 -->
          <view
            v-if="item.aid"
            @click="changeVideo"
            :class="[
              'change-video',
              { hidden: isFullScreen || isSlideStart || videoError },
            ]"
          >
            <view class="change-video-con">
              <view class="change-video-icon">
                <image src="../../static/changevideo.png"> </image>
                <view style="margin-left: 10px" class="change-video-title">
                  {{ currentAblum.ablum_name }}·{{
                    currentAblum.ablum_episodes
                  }}集全
                </view>
              </view>
              <view class="arrow">
                <image src="../../static/arrow-right.png"> </image>
              </view>
            </view>
          </view>
        </block>
      </view>
    </swiper-item>
  </swiper>
</template>

<script>
import { getVideoList } from "../../api/video";
import { formatNumberToK } from "../../utils/index";
import { VideoSwiper } from "./utils/video-swiper";
import loading from "../../components/loading/index.vue";
import ChangeVideoDialog from "../../components/changeVideoDialog/index";
import mixins from './mixins/index';
function sleep() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("1");
    }, 500);
  });
}

export default {
  components: {
    loading,
    ChangeVideoDialog
  },
  mixins: [mixins],
  data() {
    return {
      allVideoData: [], // 数据
      showChangeVideoPopup: false, // 显示选集弹框换视频
      isFullScreen: false, // 是否全屏
      swiperOptions: {
        circular: true,
        duration: 500,
        current: 0,
      },
      curQueue: [], // 当前队列
      playInfo: [], // 播放信息,包含播放时间，播放状态，播放错误
      showFullScreenTool: false, // 是否显示全屏工具栏
      currentAblum: {  // 当前剧
        ablum_name: '',
        ablum_episodes: 0,
        ablum_id: '',
      },
      start: 0 // 当前剧集索引
    };
  },

  async onLoad(option) {
    const { ablum_id, episodes_id } = option;

    await this.formatVideoData(ablum_id, episodes_id);

    let videoSwiper = new VideoSwiper({
      swiperDuration: 500,
      start: this.start || 0,
      total: this.allVideoData.length,
      getVideo: async (index) => {
        await sleep();
        let res = this.allVideoData[index];
        return res;
      },
      onSwiperOptionsChange: (data) => {
        this.swiperOptions = {
          ...data,
        };
      },
      onCurQueueChange: (data) => {
        this.curQueue = [...data];
      },
      onEndList: () => {
        uni.showToast({
          title: "到底了～～",
          icon: "none",
        });
      },
      onVideoDestroy: (videoInfo) => {
        let episode = videoInfo.episode;
        let playInfo = this.playInfo;

        playInfo[episode] = {};
        this.playInfo = [...playInfo];
      },
    });
    this.videoSwiper = videoSwiper;
  },

  onShow() {
    uni.disableUserScreenRecord();
  },
  onHide() {
    uni.enableUserScreenRecord();
  },

  methods: {
    swiperChange(e) {
      this.videoSwiper.onchange(e);

      const { currentAblum } = this;
      let currentIndex = this.videoSwiper.currentIndex;
      let currentVideo = this.videoSwiper.getCurrentVideo();

      if (currentVideo) {
        // 隐藏暂停按钮
        // const customSlider = this.$refs[`customSlider${currentVideo.id}`]
        // customSlider?.hidePauseIcon()
      }

      if (currentAblum) {
        uni.setNavigationBarTitle({
          title: `${currentAblum.ablum_name}  第${currentIndex + 1}集`,
        });
      }
    },

    // 下一个视频
    nextVideo(e) {
      if (this.isFullScreen) {
        return;
      }

      this.videoSwiper.onEnded(e);

      const { currentAblum } = this;
      let currentIndex = this.videoSwiper.currentIndex;

      if (currentAblum) {
        uni.setNavigationBarTitle({
          title: `${currentAblum.ablum_name}  第${currentIndex + 1}集`,
        });
      }
    },

    // 视频暂停/继续播放
    videoPauseOrPlay(e) {
      const { videoPause } = e.detail;
      this.videoSwiper[videoPause ? "play" : "pause"]();
    },

    // video error 回调
    error(e) {
      console.warn("video error", e);
      const { episode } = e.target.dataset;
      let playInfo = this.playInfo;

      playInfo[episode].error = true;
      uni.showToast({
        title: e.detail.errMsg,
        icon: "none",
      });
      this.playInfo = [...playInfo];
    },

    // video timeupdate 回调
    timeUpdateHandler(e) {
      const { currentTime, duration } = e.detail;
      const { episode } = e.target.dataset;
      let playInfo = this.playInfo;

      playInfo[episode].videoDuration = Math.floor(duration);
      playInfo[episode].videoCurrentTime = currentTime;

      this.playInfo = [...playInfo];
    },

    // 进度条滑动开始事件
    slideStart(e) {
      this.isSlideStart = true;
    },

    // 进度条滑动结束事件
    slideEnd(e) {
      const { videoCurrentTimeSec } = e.detail;
      this.videoSwiper.getVideoContext()?.seek(videoCurrentTimeSec);
      this.isSlideStart = false;
    },

    // 全屏进度条滑动结束
    fullScreenSlideEnd(e) {
      const { videoCurrentTimeSec } = e.detail;
      this.videoSwiper.getVideoContext()?.seek(videoCurrentTimeSec);
    },

    // 首次加载数据
    async formatVideoData(aid, eid) {
      const { videoPlayerList } = await getVideoList();
      // 当前剧信息
      const currentAblum = videoPlayerList.find((i) => i.ablum_id == aid);
      // 当前剧集
      const currentItem = videoPlayerList.find(
        (i) => i.ablum_id == aid
      )?.episodes;
      const currentIndex = currentItem?.findIndex((i) => i.episodes_id == eid);

      uni.setNavigationBarTitle({
        title: `${currentAblum.ablum_name}  第${currentItem[currentIndex].episodes_num}集`,
      });


      let playInfo = [];

      currentItem.forEach((item, index) => {
        playInfo.push({});
      });

      this.playInfo = playInfo;
      this.allVideoData = this.transformEpisodes({ episodes: currentItem, aid });
      this.currentAblum = currentAblum;
      this.ablumData = currentItem;
      this.start = currentIndex;
    },
    transformEpisodes({ episodes, aid }) {
      return episodes.map((item, index) => {
        return {
          episodesLikes: formatNumberToK(item.episodes_likes),
          episodesChasing: formatNumberToK(item.episodes_chasing),
          episodesShares: formatNumberToK(item.episodes_shares),
          aid: aid,
          eid: item.episodes_id,
          episode: index,
          id: index,
          ...item,
        }
      })
    },

    // 显示选集弹窗
    changeVideo() {
      this.showChangeVideoPopup = true;
    },

    // 隐藏选集弹窗
    cancelChangeVideo() {
      this.showChangeVideoPopup = false;
    },

    // 全屏观看
    changeFullScreen(e) {
      let context = this.videoSwiper.getVideoContext();
      if (context) {
        context.play();
        context.requestFullScreen();
        this.isFullScreen = true;
      }
    },

    // 退出全屏
    exitFullscreen(e) {
      this.videoSwiper.getVideoContext()?.exitFullScreen();
      this.isFullScreen = false;
    },

    // 全屏下，视频暂停/继续播放
    fullScreenVideoPause(e) {
      const { isVideoPlay } = e.detail;
      this.videoSwiper.getVideoContext()?.[isVideoPlay ? "pause" : "play"]();
    },

    // 全屏下点击出现全屏工具栏
    onTapVideo(e) {
      if (this.isFullScreen) {
        this.showFullScreenTool = true;
      }
    },

    // 获取视频源
    getsourceHandler(e) {
      this.videoSwiper.onGetSource(e);
    },
  },
};
</script>

<style>
@import "./style.css";
</style>